<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="关联ID" prop="patientsConsultationId">
        <el-input
          v-model="queryParams.patientsConsultationId"
          placeholder="请输入关联的问诊记录ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生ID" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="就诊状态" prop="consultationStatus">
        <el-select v-model="queryParams.consultationStatus" placeholder="请选择就诊状态">
          <el-option v-for="option in consultation_status" :key="option.value" :label="option.label"
            :value="option.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:doctorConsultation:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:doctorConsultation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:doctorConsultation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:doctorConsultation:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorConsultationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="就诊ID" align="center" prop="id" />
      <el-table-column label="关联ID" align="center" prop="patientsConsultationId" /> -->
      <el-table-column label="医生姓名" align="center">
        <template #default="scope">
          <span>{{ getDoctorName(scope.row.doctorId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="病情诊断" align="center" prop="diagnosis" />
      <el-table-column label="治疗方案" align="center" prop="treatmentPlan" />
      <el-table-column label="生活建议" align="center" prop="lifestyleAdvice" />
      <el-table-column label="问诊状态" align="center" prop="consultationStatus">
        <template #default="scope">
          <dict-tag :options="consultation_status" :value="scope.row.consultationStatus" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.consultationStatus === 0" link type="primary" icon="Edit"
            @click="handleReceive(scope.row)" v-hasPermi="['manage:doctorConsultation:edit']">
            接诊
          </el-button>
          <el-button v-else link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:doctorConsultation:edit']">
            就诊
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:doctorConsultation:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改就诊管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <!-- 患者基本信息展示区域，位于标题上方 -->
      <div v-if="tbPatientsConsultationList.length > 0">
        <el-descriptions title="患者信息" :column="2" border>
          <el-descriptions-item label="姓名">{{ tbPatientsConsultationList[0].name }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ 
              tbPatientsConsultationList[0].gender === 0 ? '男' : 
              tbPatientsConsultationList[0].gender === 1 ? '女' : 
              tbPatientsConsultationList[0].gender === 2 ? '未知' : 
              '未知' 
            }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号码">{{ tbPatientsConsultationList[0].idNumber }}</el-descriptions-item>
          <el-descriptions-item label="病情描述">{{ tbPatientsConsultationList[0].chiefComplaint }}</el-descriptions-item>
          <el-descriptions-item label="病情相关图片">
            <div v-if="tbPatientsConsultationList[0].supplementaryMedia">
              <img :src="tbPatientsConsultationList[0].supplementaryMedia" alt="图片" class="preview-image"
                @click="handleImageClick(tbPatientsConsultationList[0].supplementaryMedia)">
            </div>
            <span v-else>无</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 标题 -->
      <!--    <el-divider content-position="center">就诊人问诊信息</el-divider> -->

      <!-- 其他表单项 -->
      <el-form ref="doctorConsultationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="病情分析" prop="diagnosis">
          <el-input v-model="form.diagnosis" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="治疗方案" prop="treatmentPlan">
          <el-input v-model="form.treatmentPlan" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="建议药品">
          <el-button type="primary" @click="openDrugDialog">添加药品</el-button>
          <el-table v-if="selectedDrugs.length > 0" :data="selectedDrugs">
            <el-table-column label="药品名称" prop="drugName"></el-table-column>
            <el-table-column label="功能主治" prop="functionIndications"></el-table-column>
            <el-table-column label="用法用量" prop="usageAndDosage"></el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="生活建议" prop="lifestyleAdvice">
          <el-input v-model="form.lifestyleAdvice" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="信息补充" prop="additionalInformationNeeded">
          <el-input v-model="form.additionalInformationNeeded" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <!--  -->
      <!--  <el-table
        :data="tbPatientsConsultationList"
        :row-class-name="rowTbPatientsConsultationIndex"
        @selection-change="handleTbPatientsConsultationSelectionChange"
        ref="tbPatientsConsultation"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" prop="index" width="60" />
        
      </el-table> -->

      <!-- 底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" :loading="isLoading" :disabled="isLoading" @click="handleAIAssistedConsultation">
            {{ isLoading ? 'AI正在思考中...' : 'AI辅助问诊' }}
          </el-button>
          <el-button type="warning" @click="handleRequestAdditionalInfo">需要患者补充信息</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增图片弹窗 -->
    <el-dialog v-model="showImageModal" title="查看大图" width="60%">
      <img :src="selectedImageUrl" alt="大图预览" style="width: 100%; max-height: 70vh;">
    </el-dialog>

    <!-- 选择药品对话框 -->
    <el-dialog v-model="drugDialogVisible" title="选择药品">
      <el-table :data="drugList" @selection-change="handleDrugSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="药品名称" prop="drugName"></el-table-column>
        <el-table-column label="功能主治" prop="functionIndications"></el-table-column>
        <el-table-column label="用法用量" prop="usageAndDosage"></el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="drugDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectedDrugs">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DoctorConsultation">
import { listDoctorConsultation, getDoctorConsultation, delDoctorConsultation, addDoctorConsultation, updateDoctorConsultation } from "@/api/manage/doctorConsultation";
import { getPatients } from "@/api/manage/patients";
import { ElMessageBox, ElLoading } from 'element-plus';
import { listDrugs } from '@/api/manage/drugs';
import { getChat } from '@/api/manage/deepseekAi';
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();

const doctorConsultationList = ref([]);
const tbPatientsConsultationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbPatientsConsultation = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const showImageModal = ref(false);
const selectedImageUrl = ref('');
const { consultation_status } = proxy.useDict('consultation_status');
// 新增药品相关逻辑
const drugDialogVisible = ref(false);
const drugList = ref([]);
const selectedDrugs = ref([]);
const isLoading = ref(false);
const doctorMap = ref({}); // 用于存储医生 ID 到姓名的映射
const doctorList = ref([]); // 存储所有医生信息

const data = reactive({
  form: {
    drugs: [],
    drugId: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientsConsultationId: null,
    doctorId: null,
    diagnosis: null,
    treatmentPlan: null,
    drugId: null,
    lifestyleAdvice: null,
    additionalInformationNeeded: null,
    consultationStatus: null,
    createTime: null,
    updateTime: null
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询就诊管理列表 */
async function getList() {
  loading.value = true;
  // 获取医生信息并构建映射
  const doctorResponse = await listUser();
  doctorList.value = doctorResponse.rows;
  if (doctorList.value && doctorList.value.length > 0) {
    doctorList.value.forEach(doctor => {
      doctorMap.value[doctor.userId] = doctor.nickName; // 假设用户表中有 userId 和 nickName 字段
    });
  }
  console.log('打印查询条件：', queryParams.value);
  listDoctorConsultation(queryParams.value).then(response => {
    doctorConsultationList.value = response.rows;
    console.log('打印查询：', doctorConsultationList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientsConsultationId: null,
    doctorId: null,
    diagnosis: null,
    treatmentPlan: null,
    lifestyleAdvice: null,
    additionalInformationNeeded: null,
    consultationStatus: null,
    createTime: null,
    updateTime: null,
    drugs: [],
    drugId: ''
  };
  tbPatientsConsultationList.value = [];
  proxy.resetForm("doctorConsultationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加就诊管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getDoctorConsultation(_id).then(response => {
    form.value = response.data;
    const patientIds = response.data.tbPatientsConsultationList.map(item => item.patientsId);

    Promise.all(patientIds.map(patientId =>
      getPatients(patientId).then(detail => ({ patientId, detail: detail.data }))
    )).then(results => {
      const patientDetailMap = {};
      results.forEach(result => {
        patientDetailMap[result.patientId] = result.detail;
      });

      tbPatientsConsultationList.value = response.data.tbPatientsConsultationList.map(consultation => {
        const patientId = consultation.patientsId;
        const patientDetail = patientDetailMap[patientId];
        if (patientDetail) {
          return {
            ...consultation,
            id: patientDetail.id,
            name: patientDetail.name,
            gender: patientDetail.gender,
            dateOfBirth: patientDetail.dateOfBirth,
            idNumber: patientDetail.idNumber,
            contactPhone: patientDetail.contactPhone,
            address: patientDetail.address,
            emergencyContactName: patientDetail.emergencyContactName,
            emergencyContactPhone: patientDetail.emergencyContactPhone,
            createTime: patientDetail.createTime,
            updateTime: patientDetail.updateTime
          };
        }
        return consultation;
      });
      open.value = true;
      title.value = "修改就诊管理";
    }).catch(error => {
      console.error("Error fetching patient details:", error);
      proxy.$modal.msgError("获取患者详细信息时出错");
    });
  }).catch(error => {
    console.error("Error fetching doctor consultation data:", error);
    proxy.$modal.msgError("获取医生咨询数据时出错");
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["doctorConsultationRef"].validate(valid => {
    if (valid) {
      form.value.tbPatientsConsultationList = tbPatientsConsultationList.value;
      form.value.consultationStatus = 4;
      if (selectedDrugs.value.length > 0) {
        form.value.drugs = selectedDrugs.value.map(drug => ({
          drugId: drug.drugId,
          drugName: drug.drugName,
          functionIndications: drug.functionIndications,
          usageAndDosage: drug.usageAndDosage
        }));
        form.value.drugId = selectedDrugs.value.map(drug => drug.drugId).join(',');
      } else {
        form.value.drugs = [];
        form.value.drugId = '';
      }

      if (form.value.id != null) {
        updateDoctorConsultation(form.value).then(response => {
          proxy.$modal.msgSuccess("完成就诊");
          open.value = false;
          getList();
        });
      } else {
        addDoctorConsultation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除就诊管理编号为"' + _ids + '"的数据项？').then(function () {
    return delDoctorConsultation(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 就诊人问诊信息序号 */
function rowTbPatientsConsultationIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 复选框选中数据 */
function handleTbPatientsConsultationSelectionChange(selection) {
  checkedTbPatientsConsultation.value = selection.map(item => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/doctorConsultation/export', {
    ...queryParams.value
  }, `doctorConsultation_${new Date().getTime()}.xlsx`);
}

// 处理图片点击事件
const handleImageClick = (url) => {
  if (url) {
    selectedImageUrl.value = url;
    showImageModal.value = true;
  }
};

// 处理接诊操作
const handleReceive = async (row) => {
  if (row.consultationStatus === 0) {
    try {
      await ElMessageBox.confirm('是否确定接诊这个病人？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });

      const updatedRow = { ...row, consultationStatus: 1 };
      const response = await updateDoctorConsultation(updatedRow);

      if (response && response.code === 200) {
        const index = doctorConsultationList.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
          doctorConsultationList.value[index] = updatedRow;
        }
        getList();
        proxy.$modal.msgSuccess("接诊成功");
      } else {
        proxy.$modal.msgError("更新数据库失败，请稍后重试");
      }
    } catch (error) {
      console.error('接诊操作取消或出错:', error);
      proxy.$modal.msgError("接诊操作取消或出错");
    }
  }
};

// 处理需要患者补充信息操作
const handleRequestAdditionalInfo = async () => {
  try {
    await ElMessageBox.confirm('是否需要患者补充信息？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const updatedForm = { ...form.value, consultationStatus: 2 };
    const response = await updateDoctorConsultation(updatedForm);

    if (response && response.code === 200) {
      const index = doctorConsultationList.value.findIndex(item => item.id === form.value.id);
      if (index !== -1) {
        doctorConsultationList.value[index] = updatedForm;
      }
      getList();
      open.value = false;
      proxy.$modal.msgSuccess("已通知患者补充信息");
    } else {
      proxy.$modal.msgError("更新数据库失败，请稍后重试");
    }
  } catch (error) {
    console.error('操作取消或出错:', error);
    proxy.$modal.msgError("操作取消或出错");
  }
};

// AI辅助问诊
async function handleAIAssistedConsultation() {
  isLoading.value = true;
  const patient = tbPatientsConsultationList.value[0];
  if (patient) {
    const gender = patient.gender === 0 ? '男' : patient.gender === 1 ? '女' : '未知';
    const dateOfBirth = patient.dateOfBirth;
    const chiefComplaint = patient.chiefComplaint;
    const query = `你是一个专业的医生小助手，你的工作是辅助医生进行问诊，你需要根据患者的基本信息和病情描述给出病情分析和吃什么药，${gender}，${dateOfBirth}出生，病情描述：${chiefComplaint}，注意，输出只包含对病情的分析和吃什么药品。`;

    try {
      const response = await getChat(query);
      ElMessageBox.alert(response, 'AI辅助问诊结果', {
        confirmButtonText: '确定',
        width: '1600px'
      });
    } catch (error) {
      console.error("Error fetching AI consultation result:", error);
      proxy.$modal.msgError("获取AI辅助问诊结果时出错");
    }
  } else {
    proxy.$modal.msgError("没有找到患者信息");
  }
  isLoading.value = false;
}

// 打开药品选择对话框
const openDrugDialog = () => {
  drugDialogVisible.value = true;
  listDrugs().then(response => {
    drugList.value = response.rows;
  }).catch(error => {
    console.error('获取药品列表失败:', error);
  });
};

const handleDrugSelectionChange = (selection) => {
  selectedDrugs.value = selection;
};

const confirmSelectedDrugs = () => {
  drugDialogVisible.value = false;
  form.value.drugId = selectedDrugs.value.map(drug => drug.drugId).join(',');
};

// 获取医生姓名的函数
function getDoctorName(doctorId) {
  return doctorMap.value[doctorId] || '未知';
}

getList();
</script>

<style scoped>
/* 预览图片样式 */
.preview-image {
  max-width: 100px;
  max-height: 100px;
  cursor: pointer;
  transition: transform 0.2s;
}

.preview-image:hover {
  transform: scale(1.05);
}
</style>